<?php
namespace atlaxy;
use think\Response;
/**
 * 鉴权中间件
 * 在需要的控制器里加上即可
 */
class AuthRequest
{
    public static function setData($msg){
        return  [
            'code' => -1,
            'msg' => $msg
        ];
    }
    public function handle($request, \Closure $next)
    {
        if(!isset($_SERVER['HTTP_AUTHORIZATION']))return Response::create(self::setData('请携带请求头'), 'json');
        $authorization = explode(' ', $_SERVER['HTTP_AUTHORIZATION']);
        if(count($authorization)!==2)return Response::create(self::setData('请求头格式错误'), 'json');
        $jwt = new Jwt();
        $payload=$jwt->verifyToken($authorization[1]);
        if(!$payload)return Response::create(self::setData('登陆已过期'), 'json');
        $customer = Customer::find($payload['customer']);

        if(!$customer)return Response::create(self::setData('用户不存在'), 'json');
        if($customer->is_deleted)return Response::create(self::setData('用户被禁用'), 'json');
        $customer->login_at = time();
        $customer->login_ip = $request->ip();
        $customer->save(); 
        $request->customer = $customer->id;
        return $next($request);
    }
    
}